package com.example.u8test.Utils;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import com.example.u8test.gson.LoginPost;
import com.example.u8test.gson.LoginResponse;
import com.example.u8test.gson.PurchaseorderAddPost;
import com.example.u8test.gson.TokenResponse;
import com.example.u8test.gson.TradeIdResponse;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class U8 {
    private final String TAG = "U8";

    private Context context;
    private String from_account;
    private String to_account;
    private String app_key;
    private String app_secret;
    private String token_string = null;
    private String trade_id_string = null;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    //创建基本线程池
    final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 1, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(50));

    public U8(Context context, String from_account, String to_account, String app_key, String app_secret) {
        this.context = context;
        this.from_account = from_account;
        this.to_account = to_account;
        this.app_key = app_key;
        this.app_secret = app_secret;
        init();
    }

    //建立回调接口 start
    public interface U8LoginCallBack {
        void callBack(String responseJson);
    }

    private U8LoginCallBack u8LoginCallBack;

    public void setU8LoginCallBack(U8LoginCallBack u8LoginCallBack) {
        this.u8LoginCallBack = u8LoginCallBack;
    }

    public interface U8TokenCallBack {
        void callBack(String responseJson);
    }

    private U8TokenCallBack u8TokenCallBack;

    public void setU8TokenCallBack(U8TokenCallBack u8TokenCallBack) {
        this.u8TokenCallBack = u8TokenCallBack;
    }

    public interface U8TradeIdCallBack {
        void callBack(String responseJson);
    }

    private U8TradeIdCallBack u8TradeIdCallBack;

    public void setU8TradeIdCallBack(U8TradeIdCallBack u8TradeIdCallBack) {
        this.u8TradeIdCallBack = u8TradeIdCallBack;
    }
    //建立回调接口 end


    public void init() {
        getToken();
    }

    public void getToken() {

        if (goToNetWork()) {

            Runnable tokenRunnable = new Runnable() {
                @Override
                public void run() {
                    try {

                        String token_url = "https://api.yonyouup.com/system/token?from_account=" + from_account + "&app_key=" + app_key + "&app_secret=" + app_secret;

                        final Request request = new Request.Builder()
                                .url(token_url)
                                .get()
                                .build();
                        Call call = setCard().newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, final IOException e) {

                                Log.i("获取Token失败：", e.getMessage());
                            }

                            @Override
                            public void onResponse(Call call, Response response)
                                    throws IOException {
                                final String res = response.body().string();
                                Gson gson = new Gson();
                                TokenResponse tokenResponseGson = gson.fromJson(res, TokenResponse.class);
                                token_string = tokenResponseGson.getToken().getId();
                                showNotice("获取到的Token", token_string);
                                if (u8TokenCallBack != null) {
                                    u8TokenCallBack.callBack(token_string);
                                }
                                getTradeId();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            threadPoolExecutor.execute(tokenRunnable);

        }

    }

    //获取交易号
    public void getTradeId() {

        if (goToNetWork()) {

            Runnable tokenRunnable = new Runnable() {
                @Override
                public void run() {
                    try {

                        String trade_id_url = "https://api.yonyouup.com/system/tradeid?from_account=" + from_account + "&app_key=" + app_key + "&app_secret=" + app_secret + "&token=" + token_string;

                        final Request request = new Request.Builder()
                                .url(trade_id_url)
                                .get()
                                .build();
                        Call call = setCard().newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, final IOException e) {

                                Log.i("获取TradeId失败：", e.getMessage());
                            }

                            @Override
                            public void onResponse(Call call, Response response)
                                    throws IOException {
                                final String res = response.body().string();
                                Gson gson = new Gson();
                                TradeIdResponse tradeIdResponse = gson.fromJson(res, TradeIdResponse.class);
                                if (tradeIdResponse.getErrcode().equals("0")) {
                                    trade_id_string = tradeIdResponse.getTrade().getId();
                                    showNotice("获取到的TradeId", trade_id_string);
                                    if (u8TradeIdCallBack != null) {
                                        u8TradeIdCallBack.callBack(trade_id_string);
                                    }
                                } else {
                                    showNotice("获取TradeId失败：", tradeIdResponse.getErrcode() + tradeIdResponse.getErrmsg());
                                    trade_id_string = tradeIdResponse.getTrade().getId();
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            threadPoolExecutor.execute(tokenRunnable);

        }

    }

    public void login_v2(String user_id, String password) {

        if (goToNetWork() && token_string != null && trade_id_string != null) {

            Runnable loginRunnable = new Runnable() {
                @Override
                public void run() {
                    try {

                        String login_v2_url = "https://api.yonyouup.com/api/user/login_v2?from_account=" + from_account + "&to_account=" + to_account + "&app_key=" + app_key + "&token=" + token_string + "&tradeid=" + trade_id_string;
                        String loginPostJson = "{\n" +
                                "    \"user\": {\n" +
                                "        \"user_id\": \"" + user_id + "\",\n" +
                                "        \"password\": \"" + password + "\"\n" +
                                "    }\n" +
                                "}";
                        Log.d(TAG, "run: " + loginPostJson);

                        RequestBody requestBody = RequestBody.create(JSON, loginPostJson);

                        final Request request = new Request.Builder()
                                .url(login_v2_url)
                                .post(requestBody)
                                .build();
                        Call call = setCard().newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, final IOException e) {

                                Log.i("登陆失败：", e.getMessage());
                            }

                            @Override
                            public void onResponse(Call call, Response response)
                                    throws IOException {
                                final String res = response.body().string();
                                Gson gson = new Gson();
                                LoginResponse loginResponseGson = gson.fromJson(res, LoginResponse.class);
                                String errcode = loginResponseGson.getErrcode();
                                if (errcode.equals("0")) {
                                    showNotice("登陆成功", loginResponseGson.getErrmsg());
                                    if (u8LoginCallBack != null) {
                                        u8LoginCallBack.callBack(res);
                                    }
                                } else {
                                    showNotice("登陆失败2", loginResponseGson.getErrmsg());
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            threadPoolExecutor.execute(loginRunnable);

        }
    }


    private void postJsonToU8Server(String url, String json,String callBackType) {

        Runnable loginRunnable = new Runnable() {
            @Override
            public void run() {
                try {

                    RequestBody requestBody = RequestBody.create(JSON, json);

                    final Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    Call call = setCard().newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, final IOException e) {

                            Log.i("POST失败：", e.getMessage());
                        }

                        @Override
                        public void onResponse(Call call, Response response)
                                throws IOException {
                            final String res = response.body().string();

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        threadPoolExecutor.execute(loginRunnable);

    }


    private void callBackHandler(String res,String callBackType){
        switch(callBackType){
            case:
                break;
        }
    }


    public void addPurchaseOrder(PurchaseorderAddPost purchaseorderAddPost) {

        if (goToNetWork() && token_string != null && trade_id_string != null) {

            Runnable loginRunnable = new Runnable() {
                @Override
                public void run() {
                    try {

                        String purchase_order_add_url = "https://api.yonyouup.com/api/purchaseorder/add?from_account=" + from_account + "&to_account=" + to_account + "&app_key=" + app_key + "&token=" + token_string + "&tradeid=" + trade_id_string;
                        Gson gson = new Gson();
                        String loginPostJson = gson.toJson(purchaseorderAddPost, PurchaseorderAddPost.class);
                        Log.d(TAG, "run: " + loginPostJson);

                        RequestBody requestBody = RequestBody.create(JSON, loginPostJson);

                        final Request request = new Request.Builder()
                                .url(purchase_order_add_url)
                                .post(requestBody)
                                .build();
                        Call call = setCard().newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, final IOException e) {

                                Log.i("登陆失败：", e.getMessage());
                            }

                            @Override
                            public void onResponse(Call call, Response response)
                                    throws IOException {
                                final String res = response.body().string();
                                Gson gson = new Gson();
                                LoginResponse loginResponseGson = gson.fromJson(res, LoginResponse.class);
                                String errcode = loginResponseGson.getErrcode();
                                if (errcode.equals("0")) {
                                    showNotice("登陆成功", loginResponseGson.getErrmsg());
                                    if (u8LoginCallBack != null) {
                                        u8LoginCallBack.callBack(res);
                                    }
                                } else {
                                    showNotice("登陆失败2", loginResponseGson.getErrmsg());
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            threadPoolExecutor.execute(loginRunnable);

        }
    }


    public boolean goToNetWork() {
        // TODO Auto-generated method stub
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info == null || !info.isAvailable()) {
            new AlertDialog.Builder(context).setTitle("提醒：").setMessage("抱歉，目前无法连接网络。\n请检查您的手机网络连接！").setPositiveButton("打开网络设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Intent intent = null;
                    //判断手机系统的版本  即API大于10 就是3.0或以上版本
                    if (android.os.Build.VERSION.SDK_INT > 10) {
                        intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                    } else {
                        intent = new Intent();
                        ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
                        intent.setComponent(component);
                        intent.setAction("android.intent.action.VIEW");
                    }
                    context.startActivity(intent);
                }
            }).setNegativeButton("知道了!", null).show();
            return false;
        } else {
            //new AlertDialog.Builder(this).setMessage("网络正常可以使用").setPositiveButton("Ok", null).show();
            return true;
        }
    }

    //读取https证书
    public OkHttpClient setCard() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            String certificateAlias = Integer.toString(0);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(context.getAssets().open("api-yonyouup-com.pem")));//拷贝好的证书
            SSLContext sslContext = SSLContext.getInstance("TLS");
            final TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init
                    (
                            null,
                            trustManagerFactory.getTrustManagers(),
                            new SecureRandom()
                    );
            builder.sslSocketFactory(sslContext.getSocketFactory());
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.build();
    }

    private void showNotice(String title, String msg) {
        Log.d(title, "showNotice: " + msg);
    }

}
